package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.dao.CourseDao;
import com.qf.dao.OrderDao;
import com.qf.dao.StudentDao;
import com.qf.entity.TbCourse;
import com.qf.entity.TbOrder;
import com.qf.service.OrderService;
import com.qf.utils.AliPayTools;
import com.qf.utils.ResultMsg;
import com.qf.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;
@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, TbOrder> implements OrderService {
    @Autowired(required = false)
    CourseDao courseDao;
    @Autowired(required = false)
    StudentDao studentDao;
    @Autowired
    AliPayTools aliPayTools;

    @Transactional
    @Override
    public ResultMsg generate(int cid, HttpServletRequest request) {
        String token=request.getHeader("token");
        String studentId = TokenUtils.getStudentId(token);
        String oid= UUID.randomUUID().toString();
        TbCourse tbCourse = courseDao.selectById(cid);
        TbOrder tbOrder = new TbOrder(oid,Integer.valueOf(studentId), tbCourse.getCourseId(),new Date(),0,null);
        boolean b=this.saveOrUpdate(tbOrder);
        if(!b){
            throw new RuntimeException("订单生成失败");
        }

        //支付
        String form=aliPayTools.pay(oid,tbCourse.getCoursePrice());
        return ResultMsg.success(form);
    }
}
